package me.zhengjie.beetlsql;

import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Field;
import javax.persistence.Column;
import javax.persistence.Table;
import org.beetl.sql.core.UnderlinedNameConversion;

/**
 * @author daihy Created on 2016/1/8.
 */
public class JpaNameConversion extends UnderlinedNameConversion {

  @Override
  public String getTableName(Class<?> c) {
    Table t = c.getAnnotation(Table.class);
    return t.name();
  }

  @Override
  public String getColName(Class<?> c, String attrName) {
    Field[] fields = c.getDeclaredFields();
    for (Field field : fields) {
      if (field.getName().equals(attrName)) {
        Column columnAnnotation = field.getAnnotation(Column.class);
        if (columnAnnotation != null && StrUtil.isNotBlank(columnAnnotation.name())) {
          return columnAnnotation.name();
        }
        break;
      }
    }
    return super.getColName(c, attrName);
  }

  /**
   * todo 缓存结果
   *
   * @param c
   * @param colName
   * @return
   */
  @Override
  public String getPropertyName(Class<?> c, String colName) {
    Field[] fields = c.getDeclaredFields();
    for (Field field : fields) {
      Column columnAnnotation = field.getAnnotation(Column.class);
      if (columnAnnotation != null && colName.equalsIgnoreCase(columnAnnotation.name())) {
        return field.getName();
      }
    }
    return super.getPropertyName(c, colName);
  }
}
